<script setup lang="ts">
import { computed, onBeforeMount, reactive, ref } from 'vue';
import { $t } from '@/locales';
import { loginModuleRecord } from '@/constants/app';
import { useRouterPush } from '@/hooks/common/router';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { getCode } from '@/service/api';
import { captcha as getCaptcha } from '@/utils/captcha';
import { getServiceBaseURL } from '@/utils/service';
import { useThemeStore } from '@/store/modules/theme';
const captcha = ref({
  enable: false,
  codeImg:
    ''
});
const themeStore = useThemeStore();

const fetchCaptchCode = () => {
  // 验证码
  getCode().then(res => {
    const { data } = res;
    captcha.value.enable = data.captchaEnabled;
    captcha.value.codeImg = `data:image/gif;base64,${data.img}`;
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    model.uuid = data?.uuid;
  });
};
onBeforeMount(() => {
  fetchCaptchCode();
});

defineOptions({
  name: 'PwdLogin'
});

const authStore = useAuthStore();
const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useNaiveForm();

interface FormModel {
  username: string;
  password: string;
  uuid?: string;
  code?: string;
}

const model: FormModel = reactive({
  username: 'admin',
  password: 'admin123',
  uuid: '',
  code: ''
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale reactive, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    username: {
      required: true,
      message: $t('form.userName.invalid'),
      trigger: 'blur'
    },
    password: formRules.pwd
  };
});
const showModal = ref(false);
async function handleSubmit() {
  // console.log(themeStore.darkMode);
  showModal.value = true;
  setTimeout(() => {
    getCaptcha(
      {
        bindEl: '#box'
      },
      {
        sliderTitleText: '拖动滑块完成拼图',
        theme: themeStore.darkMode ? 'dark' : 'night'
      },
      async res => {
        // console.log(res.data.id);
        showModal.value = false;
        await validate();
        await authStore.login(model.username, model.password, model.code, res.data.id, fetchCaptchCode);
      },
      () => {},
      () => {
        showModal.value = false;
      }
    );
  }, 100);
  // // config 对象为TAC验证码的一些配置和验证的回调
  // const { baseURL } = getServiceBaseURL(import.meta.env, true);
  // const config = {
  //   // 生成接口 (必选项,必须配置, 要符合tianai-captcha默认验证码生成接口规范)
  //   requestCaptchaDataUrl: `${baseURL}/gen`,
  //   // 验证接口 (必选项,必须配置, 要符合tianai-captcha默认验证码校验接口规范)
  //   validCaptchaUrl: `${baseURL}/check`,
  //   // 验证码绑定的div块 (必选项,必须配置)
  //   bindEl: '#box',
  //   // 验证成功回调函数(必选项,必须配置)
  //   validSuccess: (res, c, tac) => {
  //     // 销毁验证码服务
  //     tac.destroyWindow();
  //     console.log('验证成功，后端返回的数据为', res);
  //     // 调用具体的login方法
  //     // login(res.data.token);
  //   },
  //   // 验证失败的回调函数(可忽略，如果不自定义 validFail 方法时，会使用默认的)
  //   validFail: (res, c, tac) => {
  //     console.log('验证码验证失败回调...');
  //     // 验证失败后重新拉取验证码
  //     tac.reloadCaptcha();
  //   },
  //   // 刷新按钮回调事件
  //   btnRefreshFun: (el, tac) => {
  //     console.log('刷新按钮触发事件...');
  //     tac.reloadCaptcha();
  //   },
  //   // 关闭按钮回调事件
  //   btnCloseFun: (el, tac) => {
  //     console.log('关闭按钮触发事件...');
  //     tac.destroyWindow();
  //   }
  // };
  // // 一些样式配置， 可不传
  // const style = {
  //   logoUrl: null // 去除logo
  //   // logoUrl: "/xx/xx/xxx.png" // 替换成自定义的logo
  // };
  // // 参数1 为 tac文件是目录地址， 目录里包含 tac的js和css等文件
  // // 参数2 为 tac验证码相关配置
  // // 参数3 为 tac窗口一些样式配置
  // window
  //   .initTAC('/public/captcha', config, style)
  //   .then(tac => {
  //     tac?.init(); // 调用init则显示验证码
  //   })
  //   .catch(e => {
  //     console.log('初始化tac失败', e);
  //   });

  // await validate();
  // await authStore.login(model.username, model.password, model.code, model.uuid, fetchCaptchCode);
}

// type AccountKey = 'super' | 'admin' | 'user';

// interface Account {
//   key: AccountKey;
//   label: string;
//   username: string;
//   password: string;
//   code: string;
//   uuid: string;
// }

// const accounts = computed<Account[]>(() => [
//   {
//     key: 'super',
//     label: $t('page.login.pwdLogin.superAdmin'),
//     userName: 'Super',
//     password: '123456'
//   },
//   {
//     key: 'admin',
//     label: $t('page.login.pwdLogin.admin'),
//     userName: 'Admin',
//     password: '123456'
//   },
//   {
//     key: 'user',
//     label: $t('page.login.pwdLogin.user'),
//     userName: 'User',
//     password: '123456'
//   }
// ]);

// async function handleAccountLogin(account: Account) {
//   await authStore.login(account.username, account.password);
// }
const handleMaskClick = () => {
  showModal.value = true;
};
</script>

<template>
  <NModal v-model:show="showModal" @on-mask-click="handleMaskClick">
    <div id="box"></div>
  </NModal>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
    <NFormItem path="username">
      <NInput v-model:value="model.username" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem v-if="captcha.enable" path="code">
      <div class="w-full flex-y-center gap-16px">
        <NInput
          v-model:value="model.code"
          type="text"
          show-password-on="click"
          :placeholder="$t('page.login.common.passwordPlaceholder')"
        />
        <img class="h-38px cursor-pointer border-rd" :src="captcha.codeImg" :onclick="fetchCaptchCode" />
      </div>
    </NFormItem>
    <NSpace vertical :size="10">
      <div class="flex-y-center justify-between">
        <NCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</NCheckbox>
        <NButton quaternary @click="toggleLoginModule('reset-pwd')">
          {{ $t('page.login.pwdLogin.forgetPassword') }}
        </NButton>
      </div>
      <NButton type="primary" size="large" block :loading="authStore.loginLoading" @click="handleSubmit">登录</NButton>
      <!--
 <div class="flex-y-center justify-between gap-12px">
        <NButton class="flex-1" block @click="toggleLoginModule('code-login')">
          {{ $t(loginModuleRecord['code-login']) }}
        </NButton>
        <NButton class="flex-1" block @click="toggleLoginModule('register')">
          {{ $t(loginModuleRecord.register) }}
        </NButton>
      </div>
-->
      <NDivider class="text-14px text-#666 !m-0">更多登录方式</NDivider>
      <div class="flex-center gap-10px pb-5px">
        <NButton round block size="large">
          <template #icon>
            <SvgIcon class="text-14px" icon="bytesize:reload" />
          </template>
          其他登录方式
        </NButton>
      </div>
      <!--
 <div class="flex-center gap-12px">
        <NButton v-for="item in accounts" :key="item.key" type="primary" @click="handleAccountLogin(item)">
          {{ item.label }}
        </NButton>
      </div>
-->
    </NSpace>
  </NForm>
</template>

<style scoped></style>
